<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = '';
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>项目状态配置</div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column type="index" label="序号" width="80px"></el-table-column>

        <el-table-column
          label="名称"
          prop="name"
          v-show="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="代号"
          prop="code"
          v-show="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="排序"
          prop="sort"
          v-show="header_list[0].showTable"
        ></el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button @click="edit_list({ item: scope.row, type: 1 })">编辑</el-button>
            <el-button @click="edit_list({ item: scope.row, type: 2 })">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addtaskStatusConfig)"
    >
      <template #title
        ><h4 v-if="add_form_data.id == ''">新增状态</h4>
        <h4 v-else>编辑状态</h4></template
      >
      <template #default>
        <el-form
          ref="addtaskStatusConfig"
          :model="add_form_data"
          :rules="rules"
          label-width="120"
        >
          <el-form-item prop="name" label="状态名称">
            <el-input
              v-model="add_form_data.name"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item prop="code" label="状态代号">
            <el-input
              v-model="add_form_data.code"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input
              v-model="add_form_data.sort"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addtaskStatusConfig)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit(addtaskStatusConfig)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onMounted, ref, onUnmounted, computed } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const list = ref();
const max_height = ref();
const loading = ref(false);
const height_size = ref(1);
const show_box = ref();
const addtaskStatusConfig = ref<FormInstance>();
const rules = ref({
  name: [{ required: true, message: "请输入状态名称", trigger: "blur" }],
  code: [{ required: true, message: "请选择状态代号", trigger: "change" }],
});
const header_list = ref<any>([
  {
    label: "状态名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "状态代号",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "排序",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  enterpriseId: computed(() => {
    return store.state.enterprise_id;
  }),
  name: "",
  code: "",
  sort: "",
});
const add_form_data = ref({
  id: "",
  enterpriseId: store.state.enterprise_id,
  name: "",
  code: "",
  sort: "",
});
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
  get_list();
  //   get_myProjectTaskList();
});
onUnmounted(() => {
  EventBus.off("refresh");
  EventBus.off("change_default_active");
});
const edit_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      enterpriseId: store.state.enterprise_id,
      name: e.item.name,
      code: e.item.code,
      sort: e.item.sort,
    };
    show_box.value = true;
  } else {
    ElMessageBox.confirm("确定删除该记录？", "", {
      closeOnClickModal: false,
      type: "warning",
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.taskStatusConfig + "/" + e.item.id,
            method: "delete",
          })
          .then(() => {
            ElMessage.success("操作成功！");
            setTimeout(() => {
              get_list();
            }, 1000);
          })
          .catch((err) => {
            ElMessage.error(err);
          });
      })
      .catch(() => {});
  }
};
const btn_loading = ref(false);
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      let data = JSON.parse(JSON.stringify(add_form_data.value));
      axios
        .request({
          url: serviceApi.taskStatusConfig + (data.id == "" ? "" : "/" + data.id),
          method: data.id == "" ? "post" : "put",
          data: data,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            btn_loading.value = false;
            resetForm(formEl);
            get_list();
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const get_list = () => {
  loading.value = true;
  let data = page_data.value;
  axios
    .request({
      url: serviceApi.taskStatusConfig + "/list",
      method: "post",
      data: data,
    })
    .then((res) => {
      console.log(res);
      list.value = res.data;
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
const search_key = () => {
  console.log(header_list.value);
  page_data.value = {
    enterpriseId: page_data.value.enterpriseId,
    name: header_list.value[0].value,
    code: header_list.value[1].value,
    sort: header_list.value[2].value,
  };
  get_list();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    enterpriseId: store.state.enterprise_id,
    name: "",
    code: "",
    sort: "",
  };
  show_box.value = false;
};
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
